#include <iostream>
#include <list>

using namespace std;

/**
 * 观察者模式
 * 目的
 * 1. 能实现一对多的消息更新机制
 * 
 * 原理
 * 1. 利用 C++ 继承、多态的特性
*/

class Obverser {
public:
    Obverser() {}
    virtual ~Obverser() {}
    virtual void update() {}
};

class Obver1 : public Obverser
{
public:
    Obver1() {}
    virtual ~Obver1() {}
    virtual void update() { cout << "Obver1::update()\n"; }
};

class Obver2 : public Obverser
{
public:
    Obver2() {}
    virtual ~Obver2() {}
    virtual void update() { cout << "Obver2::update()\n"; }
};

class Obver3 : public Obverser
{
public:
    Obver3() {}
    virtual ~Obver3() {}
    virtual void update() { cout << "Obver3::update()\n"; }
};

class Manager
{
public:
    Manager() {}
    ~Manager() {}

    void attach(Obverser* p) {
        objs.push_back(p);
    }

    void detch(Obverser* p) {
        objs.remove(p);
    }

    void notify() {
        for(auto o : objs)
            o->update();
    }

private:
    list<Obverser*> objs;
};


int main()
{
    Manager mrg;
    Obver1* o1 = new Obver1;
    Obver2* o2 = new Obver2;
    Obver3* o3 = new Obver3;
    mrg.attach(o1);
    mrg.attach(o2);
    mrg.attach(o3);

    mrg.notify();

    delete o1;
    delete o2;
    delete o3;
    o1 = nullptr;
    o2 = nullptr;
    o3 = nullptr;
    
    return 0;
}